﻿#include "addonce.h"
#include "ui_addonce.h"

AddOnce::AddOnce(QWidget *parent,const QSqlDatabase &db) :
    QDialog(parent),_db(db),
    ui(new Ui::AddOnce)
{
    ui->setupUi(this);

    ui->check_1->setCheckState(Qt::Checked);

    ui->date->setMinimumDate(QDate::currentDate());
    ui->time->setMinimumTime(QTime::currentTime());
    currentTime=QTime::currentTime();
}

AddOnce::~AddOnce()
{
    delete ui;
}

bool AddOnce::addItem(const QDateTime &datetime, const QString &detail)
{
    QSqlQuery query(_db);
    query.prepare(QString("insert into %1 (uid,target,detail,host) values (?,?,?,?)").arg(TD_ONCE));
    query.addBindValue(QUuid::createUuid().toString());
    query.addBindValue(datetime);
    query.addBindValue(detail);
    query.addBindValue(QHostInfo::localHostName());
    return query.exec();
}

void AddOnce::on_btn_submit_clicked()
{
    QString detail=ui->detail->toPlainText();
    if(detail.isEmpty())
    {
        QMessageBox::warning(this,QStringLiteral("不能为空"),QStringLiteral("提醒内容不能为空！"));
        return;
    }

    if(ui->check_2->checkState() ==Qt::Checked )
    {
        if(ui->date->date() == QDate::currentDate() && ui->time->time() == currentTime)
        {
            QMessageBox::warning(this,QStringLiteral("时间未设置"),QStringLiteral("请设置正确的时间！"));
            return;
        }

        QDateTime dateTime(ui->date->date(),ui->time->time());
        if(!addItem(dateTime,detail))
            QMessageBox::warning(this,QStringLiteral("异常情况"),QStringLiteral("提交失败！"));
        else
            accept();
    }
    else
    {
        int hour=ui->hour->value();
        int minute=ui->minute->value();
        int second=ui->second->value();

        int sum=hour * 3600 + minute*60 + second;
        QDateTime dateTime=QDateTime::currentDateTime().addSecs(sum);
        if(!addItem(dateTime,detail))
            QMessageBox::warning(this,QStringLiteral("异常情况"),QStringLiteral("提交失败！"));
        else
            accept();
    }
}

void AddOnce::on_check_1_stateChanged(int arg1)
{
    if(arg1==Qt::Checked)
        ui->check_2->setCheckState(Qt::Unchecked);
    else
        ui->check_2->setCheckState(Qt::Checked);
}

void AddOnce::on_check_2_stateChanged(int arg1)
{
    if(arg1==Qt::Checked)
        ui->check_1->setCheckState(Qt::Unchecked);
    else
        ui->check_1->setCheckState(Qt::Checked);
}
